import Clay from '@csii/vx-clay/dist/clay-template.js';

function initConfig(attr, that) {
  if (attr.cx === -1) {
    attr.cx = that._width * 0.5;
  }
  if (attr.cy === -1) {
    attr.cy = that._height * 0.5;
  }
}

Clay.series('ui-product-summary', [
  'number',
  'json',
  '$rotate',
  function($number, $json, $rotate) {
    return {
      attrs: {
        cx: $number(-1),
        cy: $number(-1),
        data: $json(),
        radius: $number(100),
      },
      event: {
        mousemove: function(target) {
          let title;
          let content;
          if (target.subRegion === '0') {
            title = '已售出产品组';
            content = ((target.attr.data.sale / target.attr.data.amount) * 100).toFixed(2) + '%';
          } else if (target.subRegion === '1') {
            title = '未售出产品组';
            content = (((target.attr.data.amount - target.attr.data.sale) / target.attr.data.amount) * 100).toFixed(2) + '%';
          }
          this.$setHover({
            title: title,
            x: target.left,
            y: target.top,
            show: true,
            items: [
              {
                color: 'red',
                content: content,
                radius: '5',
              },
            ],
          });
        },
      },
      region: {
        default(render, attr) {
          console.log(render, attr, 'attr');
          let sale = attr.data.sale / attr.data.amount;
          initConfig(attr, this);
          let deg = $rotate(attr.cx, attr.cy, sale * Math.PI, attr.cx, attr.cy - 10);
          render('0').fillArc(deg[0], deg[1], 0, attr.radius, -0.5 * Math.PI, sale * 2 * Math.PI);
          render('1').fillArc(attr.cx, attr.cy, 0, attr.radius, -0.5 * Math.PI + sale * 2 * Math.PI, (1 - sale) * 2 * Math.PI);
        },
      },
      link: function(painter, attr) {
        // 已售出产品组占总数的份数
        let sale = attr.data.sale / attr.data.amount;
        //初始化配置
        initConfig(attr, this);
        // deg 弧形的圆心
        let deg = $rotate(attr.cx, attr.cy, sale * Math.PI, attr.cx, attr.cy - 10);

        // 绘制已售出产品组
        painter
          .config({
            fillStyle: '#ee6361',
          })
          .fillArc(deg[0], deg[1], 0, attr.radius, -0.5 * Math.PI, sale * 2 * Math.PI);

        // 绘制未售出产品组
        painter
          .config({
            fillStyle: '#1fa5ff',
          })
          .fillArc(attr.cx, attr.cy, 0, attr.radius, -0.5 * Math.PI + sale * 2 * Math.PI, (1 - sale) * 2 * Math.PI);
      },
    };
  },
]);
